from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from common.notice_tools import NoticeTools
from app.auth.models import AuthUsers, AuthRoles, AuthPermissions
from app.auth.schemas import CreateUser, ModifyUser, ModifyUserIsActive, DeleteUser, CreateRole, ModifyRole, DeleteRole
from common.database import get_db
from common.utils import random_generator
from common.redispy import redispy
from core.logger import logger
from core.response import resp_200, resp_400
from core.security import security, permission_checker


router = APIRouter()


@router.get("/users", summary="获取用户列表信息", description="平台管理-授权管理-用户管理")
async def get_auth_users(field: str = Query("all"), value: str = Query(""), page: int = Query(1, ge=1),
                         per_page: int = Query(10, ge=0), db: Session = Depends(get_db), user=Depends(permission_checker)):
    if per_page:
        data = AuthUsers.get_user_roles_paginate(db, page, per_page, field, value)
    else:
        data = AuthUsers.get_entries(db)
    return resp_200(data)


# @router.get('/users', summary="获取用户列表信息", description="平台管理-授权管理-用户管理")
# async def get_host_info_search(field: str = Query("all"), value: str = Query(""), page: int = Query(1, ge=1),
#                                per_page: int = Query(10, ge=0), db: Session = Depends(get_db)):
#     result = AuthUsers.filter_by_field_search(db, page, per_page, field, value)
#     if not result:
#         message = "get user search failed"
#         logger.error(f"{message} => page:{page} per_page:{per_page} field:{field} value:{value}")
#         return resp_400(message)
#     return resp_200(result)


@router.post("/user", summary="新建用户", description="平台管理-授权管理-用户管理")
async def post_auth_user(create_user: CreateUser, db: Session = Depends(get_db), user=Depends(permission_checker)):
    if AuthUsers.get_by_username(db, create_user.username):
        return resp_400("用户已存在")

    password = random_generator()
    user = AuthUsers.add(db, {'username': create_user.username, 'nick_name': create_user.nick_name, 'ldap': 'mysql',
                              'email': create_user.email, 'mobile': create_user.mobile,
                              'hash_password': security.create_password_hash(password),
                              'is_superuser': create_user.is_superuser, 'is_active': create_user.is_active})
    user.auth_roles = db.query(AuthRoles).filter(AuthRoles.uuid.in_(create_user.user_roles)).all()
    db.commit()
    if not AuthUsers.get_by_username(db, create_user.username):
        return resp_400("创建用户失败")

    NoticeTools.email.s(to_users=["boll.lai@welab-inc.com"], subject="devops管理系统登录方式",
                        body=f"用户:{create_user.username} 密码:{password}").apply_async()

    return resp_200("创建用户成功")


@router.put("/user", summary="修改用户信息", description="平台管理-授权管理-用户管理")
async def put_auth_user(modify_user: ModifyUser, db: Session = Depends(get_db)):
    user = db.query(AuthUsers).filter(AuthUsers.username == modify_user.username).first()
    if not user:
        resp_400()

    # 更新数据库
    user.username = modify_user.username
    user.nick_name = modify_user.nick_name
    user.email = modify_user.email
    user.mobile = modify_user.mobile
    user.is_superuser = modify_user.is_superuser
    user.is_active = modify_user.is_active
    user.auth_roles = db.query(AuthRoles).filter(AuthRoles.uuid.in_(modify_user.user_roles)).all()
    db.commit()

    return resp_200()


@router.patch("/user", summary="修改用户狀態", description="平台管理-授权管理-用户管理")
async def patch_auth_user(modify_User_is_active: ModifyUserIsActive, db: Session = Depends(get_db), user=Depends(permission_checker)):
    user = db.query(AuthUsers).filter(AuthUsers.uuid == modify_User_is_active.uuid).first()
    if not user:
        resp_400()
        
    # 更新数据库
    user.is_active = modify_User_is_active.is_active
    db.commit()
    
    # 用户关闭激活，则清理redis里面之前的token
    if not modify_user.is_active:
        redispy.clean_token(user.username)
        
    return resp_200()


@router.delete("/user", summary="删除用户", description="平台管理-授权管理-用户管理")
async def delete_auth_user(delete_user: DeleteUser, db: Session = Depends(get_db), user=Depends(permission_checker)):
    user = db.query(AuthUsers).filter(AuthUsers.uuid == delete_user.uuid).first()
    if not user:
        resp_400()

    user.delete(db)
    
    # 清理token
    redispy.clean_token(user.username)
        
    return resp_200()


@router.get("/roles", summary="获取角色列表信息", description="平台管理-授权管理-角色管理")
async def get_auth_roles(field: str = Query("all"), value: str = Query(""), page: int = Query(1, ge=1),
                         per_page: int = Query(10, ge=0), db: Session = Depends(get_db), user=Depends(permission_checker)):
    if per_page:
        data = AuthRoles.get_role_permissions_paginate(db, page, per_page, field, value)
    else:
        data = AuthRoles.get_entries(db)
    return resp_200(data)


@router.post("/role", summary="新建角色", description="平台管理-授权管理-角色管理")
async def post_auth_role(create_role: CreateRole, db: Session = Depends(get_db), user=Depends(permission_checker)):
    if AuthRoles.get_by_role_name(db, create_role.role_name):
        return resp_400()

    AuthRoles.save(db, {'role_name': create_role.role_name, 'description': create_role.description})
    # role = AuthRoles(**{'role_name': create_role.role_name, 'description': create_role.description})
    # role.auth_permissions = db.query(AuthPermissions).filter(
    #     AuthPermissions.uuid.in_(create_role.role_permissions)).all()
    # db.commit()
    if not AuthRoles.get_by_role_name(db, create_role.role_name):
        return resp_400()

    return resp_200()


@router.put("/role", summary="修改角色", description="平台管理-授权管理-角色管理")
async def put_auth_role(modify_role: ModifyRole, db: Session = Depends(get_db), user=Depends(permission_checker)):
    role = db.query(AuthRoles).filter(AuthRoles.uuid == modify_role.uuid).first()
    if not role:
        return resp_400()
    role.role_name = modify_role.role_name
    role.description = modify_role.description
    role.auth_permissions = db.query(AuthPermissions).filter(
        AuthPermissions.uuid.in_(modify_role.role_permissions)).all()
    db.commit()
    return resp_200()


@router.delete("/role", summary="删除角色", description="平台管理-授权管理-角色管理")
async def delete_auth_role(delete_role: DeleteRole, db: Session = Depends(get_db), user=Depends(permission_checker)):
    role = db.query(AuthRoles).filter(AuthRoles.uuid == delete_role.uuid).first()
    if not role:
        return resp_400()
    role.delete(db)
    return resp_200()


@router.get("/permissions", summary="获取权限列表信息", description="平台管理-授权管理-权限管理")
def get_auth_permissions(field: str = Query("all"), value: str = Query(""), page: int = Query(1, ge=1),
                         per_page: int = Query(10, ge=0), db: Session = Depends(get_db), user=Depends(permission_checker)):
    if per_page:
        data = AuthPermissions.get_paginate(db, page, per_page, field, value)
    else:
        data = AuthPermissions.get_entries(db)
    return resp_200(data)


@router.get("/role_permissions", summary="获取角色权限列表信息", description="平台管理-授权管理-角色管理")
def get_auth_role_permissions(field: str = Query("all"), value: str = Query(""), page: int = Query(1, ge=1),
                         per_page: int = Query(10, ge=0), db: Session = Depends(get_db), user=Depends(permission_checker)):
    if per_page:
        data = AuthPermissions.get_paginate(db, page, per_page, field, value)
    else:
        data = AuthPermissions.get_entries(db)
    return resp_200(data)

# from app.auth.tasks import create_order
#
#
# @router.get("/task_test", summary="celery异步测试", description="celery异步测试")
# def get_task_test():
#     create_order.delay("boll", 0)
#     # if per_page:
#     #     data = AuthPermissions.get_paginate(db, page, per_page)
#     # else:
#     #     data = AuthPermissions.get_entries(db)
#     return resp_200()
